package com.xkspringmvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {
	private static Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		String url = request.getRequestURL().toString();
		String username = (String) request.getSession().getAttribute("username");
		
		// 无需登录，允许访问的地址
		String[] allowUrls = new String[] { "/user/toRegister", "/user/register", "/user/toLogin",
				"/user/login" };
		for (String strUrl : allowUrls) {
			if (url.contains(strUrl)) {
				return true;
			}
		}

		if (username != null) {
			return true;
		}
		
		// 未登录，跳转到登录页面
		request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request, response);
		log.error("用户未登录！");
		return false;
	}

}
